package com.xuanzheng.company.dao.impl;

import com.xuanzheng.company.dao.UserDao;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.util.DBUtil;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public User findByPhone(String phone) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE phone = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, phone);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setGender(rs.getString("gender"));
                user.setAge(rs.getInt("age"));
                user.setPhone(rs.getString("phone"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setAddress(rs.getString("address"));
                user.setIdCard(rs.getString("id_card"));
                user.setRole(rs.getInt("role"));
                user.setCompanyId(rs.getString("company_id"));
                user.setEmployeeNumber(rs.getString("employee_number"));
                user.setStatus(rs.getInt("status"));
                
                // 如果是公司负责人，则查询公司信息
                if (user.getRole() == 1) {
                    user.setCompanyName(rs.getString("company_name"));
                    user.setCompanyAddress(rs.getString("company_address"));
                    user.setCompanyPhone(rs.getString("company_phone"));
                    user.setCompanyCreditCode(rs.getString("company_credit_code"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return user;
    }

    @Override
    public User findById(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setGender(rs.getString("gender"));
                user.setAge(rs.getInt("age"));
                user.setPhone(rs.getString("phone"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setAddress(rs.getString("address"));
                user.setIdCard(rs.getString("id_card"));
                user.setRole(rs.getInt("role"));
                user.setCompanyId(rs.getString("company_id"));
                user.setEmployeeNumber(rs.getString("employee_number"));
                user.setStatus(rs.getInt("status"));
                
                // 如果是公司负责人，则查询公司信息
                if (user.getRole() == 1) {
                    user.setCompanyName(rs.getString("company_name"));
                    user.setCompanyAddress(rs.getString("company_address"));
                    user.setCompanyPhone(rs.getString("company_phone"));
                    user.setCompanyCreditCode(rs.getString("company_credit_code"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return user;
    }

    @Override
    public boolean addNormalUser(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO user (id, name, gender, age, phone, password, email, address, id_card, role, company_id, employee_number, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 生成唯一ID
            String id = IdGenerator.generateId();
            user.setId(id);
            
            pstmt.setString(1, user.getId());
            pstmt.setString(2, user.getName());
            pstmt.setString(3, user.getGender());
            pstmt.setInt(4, user.getAge());
            pstmt.setString(5, user.getPhone());
            pstmt.setString(6, user.getPassword());
            pstmt.setString(7, user.getEmail());
            pstmt.setString(8, user.getAddress());
            pstmt.setString(9, user.getIdCard());
            pstmt.setInt(10, 0); // 角色为普通用户
            pstmt.setString(11, user.getCompanyId());
            pstmt.setString(12, user.getEmployeeNumber());
            pstmt.setInt(13, user.getStatus());

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public boolean addCompanyManager(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO user (id, name, gender, age, phone, password, email, address, id_card, role, " +
                    "company_name, company_address, company_phone, company_credit_code, company_id, employee_number, status) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);

            // 生成唯一ID
            String id = IdGenerator.generateId();
            user.setId(id);
            
            pstmt.setString(1, user.getId());
            pstmt.setString(2, user.getName());
            pstmt.setString(3, user.getGender());
            pstmt.setInt(4, user.getAge());
            pstmt.setString(5, user.getPhone());
            pstmt.setString(6, user.getPassword());
            pstmt.setString(7, user.getEmail());
            pstmt.setString(8, user.getAddress());
            pstmt.setString(9, user.getIdCard());
            pstmt.setInt(10, 1); // 角色为公司负责人
            pstmt.setString(11, user.getCompanyName());
            pstmt.setString(12, user.getCompanyAddress());
            pstmt.setString(13, user.getCompanyPhone());
            pstmt.setString(14, user.getCompanyCreditCode());
            pstmt.setString(15, user.getCompanyId());
            pstmt.setString(16, user.getEmployeeNumber());
            pstmt.setInt(17, user.getStatus());

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public boolean updatePassword(String phone, String newPassword) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE user SET password = ? WHERE phone = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, newPassword);
            pstmt.setString(2, phone);

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }

    @Override
    public boolean checkAdmin(String adminId, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM admin WHERE admin_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, adminId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 获取数据库中存储的密码
                String storedPassword = rs.getString("password");
                // 验证输入的密码是否正确
                result = password.equals(storedPassword);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return result;
    }
    
    @Override
    public String getAdminPassword(String adminId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String password = null;

        System.out.println("UserDaoImpl.getAdminPassword - adminId: " + adminId);

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT password FROM admin WHERE admin_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, adminId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                password = rs.getString("password");
                System.out.println("UserDaoImpl.getAdminPassword - 找到密码: " + password);
            } else {
                System.out.println("UserDaoImpl.getAdminPassword - 未找到管理员账号");
            }
        } catch (SQLException e) {
            System.out.println("UserDaoImpl.getAdminPassword - SQL异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return password;
    }
    
    @Override
    public boolean updateAdminPassword(String adminId, String newPassword) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE admin SET password = ? WHERE admin_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, newPassword);
            pstmt.setString(2, adminId);

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }
    
    @Override
    public User findByNameAndIdCard(String name, String idCard) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE name = ? AND id_card = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, idCard);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setGender(rs.getString("gender"));
                user.setAge(rs.getInt("age"));
                user.setPhone(rs.getString("phone"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setAddress(rs.getString("address"));
                user.setRole(rs.getInt("role"));
                user.setIdCard(rs.getString("id_card"));
                user.setCompanyId(rs.getString("company_id"));
                user.setEmployeeNumber(rs.getString("employee_number"));
                user.setStatus(rs.getInt("status"));
                
                // 如果是公司负责人，则查询公司信息
                if (user.getRole() == 1) {
                    user.setCompanyName(rs.getString("company_name"));
                    user.setCompanyAddress(rs.getString("company_address"));
                    user.setCompanyPhone(rs.getString("company_phone"));
                    user.setCompanyCreditCode(rs.getString("company_credit_code"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return user;
    }
    
    @Override
    public User findByNameAndIdCardAndPhone(String name, String idCard, String phone) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE name = ? AND id_card = ? AND phone = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, idCard);
            pstmt.setString(3, phone);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setGender(rs.getString("gender"));
                user.setAge(rs.getInt("age"));
                user.setPhone(rs.getString("phone"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setAddress(rs.getString("address"));
                user.setRole(rs.getInt("role"));
                user.setIdCard(rs.getString("id_card"));
                user.setCompanyId(rs.getString("company_id"));
                user.setEmployeeNumber(rs.getString("employee_number"));
                user.setStatus(rs.getInt("status"));
                
                // 如果是公司负责人，则查询公司信息
                if (user.getRole() == 1) {
                    user.setCompanyName(rs.getString("company_name"));
                    user.setCompanyAddress(rs.getString("company_address"));
                    user.setCompanyPhone(rs.getString("company_phone"));
                    user.setCompanyCreditCode(rs.getString("company_credit_code"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return user;
    }
    
    @Override
    public boolean updateUser(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            StringBuilder sql = new StringBuilder("UPDATE user SET ");
            sql.append("name = ?, ");
            sql.append("gender = ?, ");
            sql.append("age = ?, ");
            sql.append("phone = ?, ");
            sql.append("password = ?, ");
            sql.append("email = ?, ");
            sql.append("address = ?, ");
            sql.append("role = ?, ");
            sql.append("company_id = ?, ");
            sql.append("employee_number = ?, ");
            sql.append("status = ? ");
            
            // 如果是公司负责人，则更新公司信息
            if (user.getRole() == 1) {
                sql.append(", company_name = ?, ");
                sql.append("company_address = ?, ");
                sql.append("company_phone = ?, ");
                sql.append("company_credit_code = ? ");
            }
            
            sql.append("WHERE id = ?");
            
            pstmt = conn.prepareStatement(sql.toString());
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getGender());
            pstmt.setInt(3, user.getAge());
            pstmt.setString(4, user.getPhone());
            pstmt.setString(5, user.getPassword());
            pstmt.setString(6, user.getEmail());
            pstmt.setString(7, user.getAddress());
            pstmt.setInt(8, user.getRole());
            pstmt.setString(9, user.getCompanyId());
            pstmt.setString(10, user.getEmployeeNumber());
            pstmt.setInt(11, user.getStatus());
            
            int paramIndex = 12;
            if (user.getRole() == 1) {
                pstmt.setString(paramIndex++, user.getCompanyName());
                pstmt.setString(paramIndex++, user.getCompanyAddress());
                pstmt.setString(paramIndex++, user.getCompanyPhone());
                pstmt.setString(paramIndex++, user.getCompanyCreditCode());
            }
            
            pstmt.setString(paramIndex, user.getId());

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }
    
    @Override
    public List<User> getAllUsers() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                User user = mapResultSetToUser(rs);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return users;
    }
    
    @Override
    public List<User> findUsersByName(String name) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE name LIKE ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + name + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                User user = mapResultSetToUser(rs);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return users;
    }
    
    @Override
    public List<User> findUsersByPhone(String phone) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE phone LIKE ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + phone + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                User user = mapResultSetToUser(rs);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return users;
    }
    
    @Override
    public List<User> findUsersByIdCard(String idCard) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE id_card LIKE ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + idCard + "%");
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                User user = mapResultSetToUser(rs);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return users;
    }
    
    @Override
    public boolean updateUserStatus(String id, int status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE user SET status = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, status);
            pstmt.setString(2, id);

            int affectedRows = pstmt.executeUpdate();
            result = (affectedRows > 0);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }

        return result;
    }
    
    @Override
    public boolean deleteUserById(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean result = false;
        
        System.out.println("UserDaoImpl.deleteUserById - 开始处理, 用户ID: " + id);
        
        try {
            conn = DBUtil.getConnection();
            
            // 直接删除用户本身，保留其他相关数据用于公司备案
            String deleteUserSQL = "DELETE FROM user WHERE id = ?";
            pstmt = conn.prepareStatement(deleteUserSQL);
            pstmt.setString(1, id);
            int userRows = pstmt.executeUpdate();
            System.out.println("删除用户记录: " + userRows + "行");
            
            result = (userRows > 0);
            
        } catch (SQLException e) {
            // 处理数据库异常
            System.err.println("数据库操作失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, null);
        }
        
        System.out.println("UserDaoImpl.deleteUserById - 处理完成, 结果: " + result);
        return result;
    }
    
    // 辅助方法：将ResultSet映射到User对象
    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getString("id"));
        user.setName(rs.getString("name"));
        user.setGender(rs.getString("gender"));
        user.setAge(rs.getInt("age"));
        user.setPhone(rs.getString("phone"));
        user.setPassword(rs.getString("password"));
        user.setEmail(rs.getString("email"));
        user.setAddress(rs.getString("address"));
        user.setIdCard(rs.getString("id_card"));
        user.setRole(rs.getInt("role"));
        user.setCompanyId(rs.getString("company_id"));
        user.setEmployeeNumber(rs.getString("employee_number"));
        user.setStatus(rs.getInt("status"));
        
        // 如果是公司负责人，则查询公司信息
        if (user.getRole() == 1) {
            user.setCompanyName(rs.getString("company_name"));
            user.setCompanyAddress(rs.getString("company_address"));
            user.setCompanyPhone(rs.getString("company_phone"));
            user.setCompanyCreditCode(rs.getString("company_credit_code"));
        }
        
        return user;
    }
} 